/*
 * Copyright 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

@file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)

package androidx.room.util

import androidx.annotation.RestrictTo
import androidx.room.ConstructedBy
import androidx.room.RoomDatabase
import androidx.room.RoomDatabaseConstructor
import kotlin.reflect.ExperimentalAssociatedObjects
import kotlin.reflect.KClass
import kotlin.reflect.findAssociatedObject

/**
 * Finds the [RoomDatabaseConstructor] of this class linked via [ConstructedBy] and invoke its
 * function to create an instance of the implementation class generated by Room of an `@Database`
 * annotated type.
 */
@OptIn(ExperimentalAssociatedObjects::class)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
fun <T : RoomDatabase> findDatabaseConstructorAndInitDatabaseImpl(klass: KClass<*>): T {
    val constructor = klass.findAssociatedObject<ConstructedBy>() as? RoomDatabaseConstructor<*>
    checkNotNull(constructor) {
        "Cannot find the associated ${RoomDatabaseConstructor::class.qualifiedName} for " +
            "${klass.qualifiedName}. Is Room annotation processor correctly configured?"
    }
    @Suppress("UNCHECKED_CAST") // Actually safe due to annotation processor enforcement
    return constructor.initialize() as T
}
